﻿using ICSharpCode.SharpZipLib.Zip;
using System;
using System.Diagnostics;
using System.IO;
using System.Net;

namespace VitaCOMupdater
{
    internal class VitaCOMupdater
    {
        private const string ERROR_OUT_FILE_PATH = "error_log_updater.txt";
        private static int exceptioncount = 0;
        private static string exceptiondata = "";

        private static void AppendException(Exception ex)
        {
            exceptiondata += "Exception #" + exceptioncount + ": " + ex.Message + "\r\n" + ex.StackTrace + "\r\n\r\n";
            exceptioncount++;
        }

        private static void Main(string[] args)
        {
            if (args.Length < 2)
                return;

            Console.WriteLine("Waiting for VitaCOMgui to close...");
            try
            {
                foreach (Process process in Process.GetProcessesByName(Path.GetFileNameWithoutExtension(args[0])))
                    process.Kill();
            }
            catch (Exception ex)
            {
                Console.WriteLine("Encountered an error while terminating VitaCOMgui! Continuing...");
                AppendException(ex);
            }

            Console.WriteLine("Downloading update package...");
            WebClient webclient = new WebClient();

            string packagepath = args[1] != "old" ?
                webclient.DownloadString("http://data.celcodioc.host22.com/vitacom/update_package_path") :
                "http://vitacom.googlecode.com/files/VitaCOMgui%201.7.4564.21106.exe";

            try
            {
                webclient.DownloadFile(packagepath, "update.dat");
            }
            catch (Exception ex)
            {
                Console.WriteLine("Encountered an error while downloading update package! Continuing...");
                AppendException(ex);
            }
            finally
            {
                webclient.Dispose();
            }

            Console.WriteLine("Applying update package...");
            try
            {
                if (args[1] != "old")
                    new FastZip().ExtractZip("update.dat", Environment.CurrentDirectory, FastZip.Overwrite.Always, null, null, null, false);

                if (File.Exists(args[0])) File.Delete(args[0]);

                if (args[1] != "old")
                    File.Move(Path.GetFileNameWithoutExtension(packagepath).Replace("%20", " ") + ".exe", args[0]);
                else File.Move("update.dat", args[0]);

                if (File.Exists("update.dat")) File.Delete("update.dat");
            }
            catch (Exception ex)
            {
                Console.WriteLine("Encountered an error while applying update package!");
                AppendException(ex);
            }

            if (!string.IsNullOrEmpty(exceptiondata))
            {
                SaveExceptions();

                Console.Write("Press any key to continue...");
                Console.ReadKey(true);
            }
            else
                Process.Start(args[0]);
        }

        private static void SaveExceptions()
        {
            try
            {
                using (StreamWriter sw = new StreamWriter(ERROR_OUT_FILE_PATH))
                    sw.Write(exceptiondata);
            }
            catch (Exception exx)
            {
                Console.WriteLine("Could not save exceptions to file!\n\n" + exx.Message + "\n" + exx.StackTrace);
            }
        }
    }
}